package com.kuang.thread.syn;

//不安全的买票
public class UnsafeBuyTicket {
    public static void main(String[] args) {
        BuyTicket buyTicket = new BuyTicket();

        new Thread(buyTicket,"牙").start();
        new Thread(buyTicket,"雏田").start();
        new Thread(buyTicket,"志乃").start();
    }
}

class BuyTicket implements Runnable {
    private int ticketNum = 10;
    private boolean flag = true;

    @Override
    public void run() {
        //买票
        while (flag) {
            buy();

        }
    }

    //synchronized 同步方法，锁的是this
   private synchronized void buy() {
        if (ticketNum > 0) {
            System.out.println(Thread.currentThread().getName() + "买票成功" + ticketNum--);
        } else {
            flag = false;
        }
       try {
           Thread.sleep(100);
       } catch (InterruptedException e) {
           e.printStackTrace();
       }
   }
}